package com.jinlejia.bbs.ui.reply;

import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.jinlejia.bbs.R;
import com.jinlejia.bbs.adapter.reply.ReplyBean;
import com.jinlejia.bbs.adapter.reply.ReplyDetailAdapter;
import com.jinlejia.bbs.bean.base.BBSUserBean;
import com.jinlejia.bbs.bean.base.InformationBean;
import com.jinlejia.bbs.bean.base.TopicBean;
import com.jinlejia.bbs.databinding.BbsActivityReplyDetailBinding;
import com.jinlejia.bbs.dialog.CommonDeleteDialog;
import com.jinlejia.bbs.help.CommonEvent;
import com.jinlejia.bbs.logic.DeleteLogic;
import com.jinlejia.bbs.logic.ReplyDetailLogic;
import com.jinlejia.bbs.logic.TakeAttentionLogic;
import com.jinlejia.bbs.ui.gambit.BBSCommentsByAnswerActivity;
import com.jinlejia.bbs.ui.mine.others.BBSOtherUserMainActivity;
import com.jinlejia.bbs.widget.mp3.AudioController;
import com.jinlejia.bbs.widget.recycler.PullInterface;

import java.util.List;

public class BBSReplyDetailActivity extends AppCompatActivity implements
        ReplyDetailLogic.LogicCallBack,
        SwipeRefreshLayout.OnRefreshListener,
        PullInterface.LoadMoreListener,
        CommonEvent.BackFilter {
    private BbsActivityReplyDetailBinding binding;
    private ViewHelper viewHelper;
    private ReplyDetailLogic logic;
    private DeleteLogic deleteLogic;
    private ReplyBean replyBean;
    private String topicCode;
    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.bbs_activity_reply_detail);
        binding.setCommonEvent(CommonEvent.obtain());
        boolean isInvite = getIntent().getBooleanExtra("isInvite",false);
        binding.inputLayout.setVisibility(View.GONE);
        TopicBean topic = getIntent().getParcelableExtra("topic");
        topicCode = topic.getTopicCode();
        viewHelper = new ViewHelper(this,topicCode, binding);
        binding.setEvent(viewHelper);
        viewHelper.initView(isInvite);
        if (replyBean==null) replyBean = new ReplyBean();
        deleteLogic = new DeleteLogic(this);
        logic = new ReplyDetailLogic(this,topicCode,replyBean,this);
        audioController = new AudioController(this);
        context = this;
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }
    private AudioController audioController;
    private ReplyDetailAdapter adapter;
    private void initView() {
        if (adapter==null){
            adapter = new ReplyDetailAdapter(this,binding.recyclerView,audioController);
            adapter.setUserInfoListener(new ReplyDetailAdapter.OnClickUserInfoListener() {
                @Override
                public void onClickUserInfo(BBSUserBean user,int position) {
                    Intent intent = new Intent();
                    intent.setClass(context, BBSOtherUserMainActivity.class);
                    intent.putExtra("pin",user.getUserPin());
                    startActivityForResult(intent,100);
                }
            });
            adapter.setListener(new ReplyDetailAdapter.OnChangeAttentionListener() {
                private TakeAttentionLogic logic;
                @Override
                public void onChangeAttention(final InformationBean bean,final int position) {
                    if (logic==null){
                        logic = new TakeAttentionLogic(context);
                    }
                    final String pin = bean.getUser().getUserPin();
                    logic.execute(pin, new TakeAttentionLogic.LogicCallBack() {
                        @Override
                        public void onResult(int result) {
                            List<InformationBean> list = replyBean.getInformationList();
                            for (InformationBean b:list) {
                                BBSUserBean user = b.getUser();
                                if (TextUtils.equals(user.getUserPin(),pin)){
                                    user.setAttentionType(result);
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
            });

            adapter.setReplyListener(new ReplyDetailAdapter.OnReplyListener() {
                @Override
                public void onReply(final InformationBean bean, final int position) {
                    Intent intent = new Intent();
                    intent.setClass(context, BBSCommentsByAnswerActivity.class);
                    intent.putExtra("answerCode",bean.getAnswerCode());
                    startActivity(intent);
                }
            });

            adapter.setDeleteListener(new ReplyDetailAdapter.DeleteListener() {
                @Override
                public void onDelete(String topicCode, String answerCode) {
                    showDeleteDialog(topicCode, answerCode);
                }
            });

            binding.recyclerView.setAdapter(adapter);
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            binding.recyclerView.setLayoutManager(layoutManager);
            binding.recyclerView.setAutoLoadMoreListener(this);
            binding.swipeRefreshLayout.setOnRefreshListener(this);
        }
        binding.swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                binding.swipeRefreshLayout.setRefreshing(true);
                logic.refresh();
            }
        });
    }

    private CommonDeleteDialog deleteDialog;
    private void showDeleteDialog(final String topicCode, final String answerCode){
        if (deleteDialog!=null){
            deleteDialog.dismiss();
            deleteDialog = null;
        }
        if (topicCode!=null){
            deleteDialog = new CommonDeleteDialog(this,"删除","确定删除这个话题吗？");
            deleteDialog.setConfirmListener(new CommonDeleteDialog.OnConfirmListener() {
                @Override
                public void confirm() {
                    deleteLogic.deleteTopic(topicCode, new DeleteLogic.CallBack() {
                        @Override
                        public void onResult(boolean result, String code) {
                            if (result){
                                setResult(RESULT_OK);
                                finish();
                            }
                        }
                    });
                }
            });

        }else if (answerCode!=null){
            deleteDialog = new CommonDeleteDialog(this,"删除","确定删除这个回答吗？");
            deleteDialog.setConfirmListener(new CommonDeleteDialog.OnConfirmListener() {
                @Override
                public void confirm() {
                    deleteLogic.deleteAnswer(answerCode, new DeleteLogic.CallBack() {
                        @Override
                        public void onResult(boolean result, String code) {
                            if (result){
                                onRefresh();
                            }
                        }
                    });
                }
            });
        }
        if (deleteDialog!=null)
            deleteDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        viewHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==100){

        }else {
            viewHelper.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        if (audioController!=null)audioController.release();
        super.onDestroy();
    }

    @Override
    public void onResult(boolean hasNextPage,boolean isDel) {
        adapter.initData(replyBean);
        if (isDel){
            binding.deleteLayout.setVisibility(View.VISIBLE);
        }else {
            binding.deleteLayout.setVisibility(View.GONE);
        }
        if (!hasNextPage){
            binding.recyclerView.setAutoLoadMoreListener(null);
        }else {
            binding.recyclerView.setAutoLoadMoreListener(this);
        }
        if (replyBean.getTopic()==null){
            return;
        }
        if (isDel){
            return;
        }
        boolean collection = replyBean.getTopic().isCollection();
        if (collection){
            binding.collectImg.setImageResource(R.mipmap.bbs_icon_liked_button);
            binding.collectTextView.setText("已收藏");
            binding.collectTextView.setTextColor(Color.parseColor("#FCCB00"));
        }else {
            binding.collectImg.setImageResource(R.mipmap.bbs_icon_like_button);
            binding.collectTextView.setTextColor(Color.parseColor("#333333"));
            binding.collectTextView.setText("收藏");
        }
        binding.swipeRefreshLayout.setRefreshing(false);
        binding.recyclerView.getAdapter().notifyDataSetChanged();
    }

    @Override
    public void onLoadMore() {
        binding.swipeRefreshLayout.setRefreshing(true);
        logic.load();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if (binding.inputLayout.getVisibility()==View.VISIBLE){
                viewHelper.hideInputLayout();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onRefresh() {
        binding.swipeRefreshLayout.setRefreshing(true);
        logic.refresh();
        setResult(RESULT_OK);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public boolean onBack() {
        hintKbTwo();
        return false;
    }

    private void hintKbTwo() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(binding.inputEditText.getWindowToken(),0);
        }
    }
    //endregion
}
